<?php

namespace App\Domain\Address\Dao;

use App\Domain\Address\Models\AddressModel;
use App\Exceptions\BadRequestException;

class AddressDao
{
    public function findByCode($code)
    {
        $data = AddressModel::where('code', $code)->first();
        return $data;
    }

        public function findByParentCode($parent_code)
    {
        $level = AddressModel::where('parent_code', $parent_code)->first();
        return $level;
    }

    /**
     * 修改地址
     * @param AddressModel $model
     * @param $param
     * @return AddressModel
     */
    public function update(AddressModel $model, $param)
    {
        $param = array_filter_null($param);
        $model->fill($param)->save();
        return $model;
    }

    /**
     * 创建地址
     * @param $params
     * @return AddressModel
     */
    public function create($params)
    {
        $params = array_filter_null($params);
        return AddressModel::create($params);
    }

    public function del($id)
    {
        $ids = explode(',',$id);
        foreach ($ids as $v){
            $data = AddressModel::where('code', $v)->first();
            $level = AddressModel::where('parent_code', $data['parent_code'])->first();
            if($level){
                throw new BadRequestException('存在子集');
                die();
            }
        }
        return AddressModel::whereIn('id', $ids)->update(['status' => '0']);
    }

}
